package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.elasticsearch.constant.EsMappingConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EsAliasEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.SysAliasEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsInitByCorpidListAndBusinessTypeListDTO;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsInitDTO;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsMappingDTO;
import com.xbongbong.paas.pojo.dto.PaasFormOriginalDataInitDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsInitVO;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.service.PaasElasticSearchService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.IModel;
import com.xbongbong.parent.es.AbstractPaasElasticSearchInit;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.ProVersionEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.service.toolbox.statistic.help.TeamHelp;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.help.InitDataHelp;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.CommunicatePlanModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.CostAdjustModel;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.FundTransferModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OtherExpenseModel;
import com.xbongbong.saas.model.OtherIncomeModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.PaymentTaskModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.SupplierCommunicateModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkReportModel;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetMappingsRequest;
import org.elasticsearch.client.indices.GetMappingsResponse;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;

/**
 * 创建时间： 2018/9/27 16:14
 * 修改时间： 2018/9/27 16:14 梁鲁江
 *
 * @author 梁鲁江
 */
@Service("paasElasticSearchService")
public class PaasElasticSearchServiceImpl extends AbstractPaasElasticSearchInit implements PaasElasticSearchService {
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private InitDataHelp initDataHelp;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private TeamHelp teamHelp;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private ContactModel contactModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private InstockModel instockModel;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private CommunicatePlanModel communicatePlanModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    private SupplierCommunicateModel supplierCommunicateModel;
    @Resource
    private WorkReportModel workReportModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private InventoryModel inventoryModel;
    @Resource
    private TransferModel transferModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private OtherIncomeModel otherIncomeModel;
    @Resource
    private OtherExpenseModel otherExpenseModel;
    @Resource
    private FundTransferModel fundTransferModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;
    @Resource
    private PaymentTaskModel paymentTaskModel;
    @Resource
    private CostAdjustModel costAdjustModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private IndexTypeModel indexTypeModel;



    private static final Logger LOG = LoggerFactory.getLogger(PaasElasticSearchServiceImpl.class);



    @Override
    public PaasFormDataEsInitVO init(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        long start = DateTimeUtil.getInt();
        try {
            Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
            if(byCorpid != null && Objects.equals(0,byCorpid)){
                paasFormDataEsInitDTO.setCorpid(null);
            }
            Integer pageSize = paasFormDataEsInitDTO.getPageSize();
            if (pageSize == null) {
                paasFormDataEsInitDTO.setPageSize(SizeConstant.PAGE_SIZE);
            }
            PaasFormDataEsMappingDTO paasFormDataEsMappingDTO = new PaasFormDataEsMappingDTO();
            BeanUtil.copyProperties(paasFormDataEsInitDTO, paasFormDataEsMappingDTO);
            String indexVersion = paasFormDataEsInitDTO.getIndexVersion();
            IndexTypeEnum indexTypeEnum = EsHelper.getIndexTypeEnum(paasFormDataEsMappingDTO);
            JSONObject mapping = getMappingMap(indexTypeEnum);
            Set<String> outKeySet = mapping.keySet();
            Set<String> dataKeySet = mapping.getJSONObject("data").getJSONObject("properties").keySet();
            JSONObject subForm = mapping.getJSONObject("data").getJSONObject("properties").getJSONObject("subForm_1");
            JSONObject subFormSec = mapping.getJSONObject("data").getJSONObject("properties").getJSONObject("subForm_2");
            Set<String> subFormKeySet = null;
            Set<String> subFormKeySecSet = null;
            if(subForm != null && !subForm.isEmpty()){
                subFormKeySet = subForm.getJSONObject("properties").keySet();
            }
            if(subFormSec != null && !subFormSec.isEmpty()){
                subFormKeySecSet = subFormSec.getJSONObject("properties").keySet();
            }
            if(Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(),paasFormDataEsInitDTO.getBusinessType()) || Objects.equals(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(),paasFormDataEsInitDTO.getBusinessType())){
                paasFormDataEsInitDTO.setFromInit(1);
            }
            String value = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ELASTICSEARCH_INDEX.getAlias(), CompanyConfigEnum.ELASTICSEARCH_INDEX.getAlias(), "0", "0", RedisTimeConstant.TEN_MINUTES);
            Set<String> corpidSet = new HashSet<>();
            if (StringUtil.isNotEmpty(value)) {
                corpidSet = new HashSet<>(JSON.parseArray(value, String.class));
            }

            Map<String, Object> params = BeanUtil.convertBean2Map(paasFormDataEsInitDTO, true,true);
            params.put("orderByStr", "id");
            boolean flag = true;
            while (flag) {
                List list = initDataHelp.getList(paasFormDataEsMappingDTO.getBusinessType(),paasFormDataEsMappingDTO.getSaasMark() ,params,paasFormDataEsInitDTO.getFromInit(), null);
                if (list == null || list.isEmpty()) {
                    flag = false;
                } else {
                    //大于上次最大的id
                    Object o = list.get(list.size() - 1);
                    PaasFormDataEntity paasFormDataEntity = (PaasFormDataEntity) o;
                    LOG.info("businessType:" + paasFormDataEsMappingDTO.getBusinessType() + " max id :" + paasFormDataEntity.getId());
                    params.put("idGte", paasFormDataEntity.getId());
                    List<InsertDTO> insertList = new ArrayList<>();
                    for (Object object : list) {
                        try {
                            PaasFormDataEntity entity = (PaasFormDataEntity) object;
                            if (corpidSet.contains(entity.getCorpid()) && Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), paasFormDataEsInitDTO.getBusinessType())) {
                                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CUSTOMER_SPECIAL;
                            }
                            InsertDTO insertDTO = new InsertDTO();
                            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
                            insertDTO.setEsId(entity.getCorpid() + "_" + entity.getId());
                            entity.setDataId(entity.getId());
                            Map<String, Object> source = BeanUtil.convertBean2Map(entity, false, true);
                            JSONObject data = (JSONObject) source.get("data");
                            if(Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(),paasFormDataEsInitDTO.getBusinessType())){
                                data.put(ProductEnum.INSTRUCTION.getAttr(),"");
                            }
                            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),paasFormDataEsInitDTO.getBusinessType())) {
                                data.remove(CustomerManagementEnum.CONTRACT_SIGN_DATE.getAttr());
                                data.remove(CustomerManagementEnum.OPPORTUNITY_ADD_DATE.getAttr());
                            }
                            // 特殊子表单内数据的清理
                            subFormDataRetain(data,subFormKeySet,subFormKeySecSet);
                            data.keySet().retainAll(dataKeySet);
                            source.keySet().retainAll(outKeySet);
                            source.put(ElasticConstant.MY_JOIN_FIELD,indexTypeEnum.getType());
                            insertDTO.setSource(source);
                            insertDTO.setIndexTypeEnum(indexTypeEnum, indexVersion);
                            insertList.add(insertDTO);
                        } catch (Exception e) {
                            LOG.error("==="+JSONObject.toJSONString(object),e);
                        }
                    }
                    if(paasFormDataEsInitDTO.isAsync()){
                        paasEsModel.insertBatchAsync(insertList,WriteRequest.RefreshPolicy.NONE,false);
                    }else{
                        paasEsModel.insertBatch(insertList,WriteRequest.RefreshPolicy.NONE,false);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("初始化失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.error("初始化成功" + paasFormDataEsInitDTO.getBusinessType());
        return paasFormDataEsInitVO;
    }


    /**
     * 初始化主type和team(paas和其他子type除外)
     * @param paasFormDataEsInitDTO
     * @return
     * @throws XbbException
     */
    @Override
    public PaasFormDataEsInitVO initAll(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
        if(byCorpid != null && Objects.equals(0,byCorpid)){
            paasFormDataEsInitDTO.setCorpid(null);
        }
        Long updateTimeStart = paasFormDataEsInitDTO.getUpdateTimeStart();
        if(updateTimeStart != null && updateTimeStart > 0 ){
            Map<String, Object> param = new HashMap<>();
            param.put("del", 0);
            param.put("status", 1);
            param.put("columns", "corpid");
            param.put("feeEndTimeStart", updateTimeStart);
            List<CompanyEntity> companyEntities = companyModel.findEntitys(param);
            Integer count = 0;
            for (CompanyEntity companyEntity : companyEntities) {
                paasFormDataEsInitDTO.setCorpid(companyEntity.getCorpid());
                for (IndexTypeEnum value : IndexTypeEnum.getAllEnum()) {
                    doInit(paasFormDataEsInitDTO, value);
                }
                count++;
                LOG.info(companyEntity.getCorpid() + "=====count====="+ count + "====size==="+companyEntities.size());
            }
        }else {
            for (IndexTypeEnum value : IndexTypeEnum.getAllEnum()) {
                doInit(paasFormDataEsInitDTO, value);
            }
        }
        LOG.info("初始化结束success=====");
        return paasFormDataEsInitVO;
    }

    @Override
    public void doInit(PaasFormDataEsInitDTO paasFormDataEsInitDTO, IndexTypeEnum value) {
        paasFormDataEsInitDTO.setBusinessType(value.getCode());
        if (Objects.equals(value.getCode(), IndexTypeEnum.IDX_FORM_DATA.getCode())) {
            paasFormDataEsInitDTO.setSaasMark(SaasMarkEnum.PAAS.getCode());
        } else {
            paasFormDataEsInitDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        }
        try {
            if ("my_team".equals(value.getType()) || "product_warehouse".equals(value.getType()) || "product_stock_info".equals(value.getType())
                    || "call_center_call_log".equals(value.getType()) || "contract_performance".equals(value.getType()) || "my_cc".equals(value.getType())
                    || "my_evaluation".equals(value.getType()) || "my_product".equals(value.getType())
                    || IndexTypeEnum.IDX_PAYMENT_BALANCE.getType().equals(value.getType())
                    || IndexTypeEnum.IDX_PAY_BALANCE.getType().equals(value.getType())
                    || IndexTypeEnum.IDX_FUND_ACCOUNT_FLOW.getType().equals(value.getType())
                    || IndexTypeEnum.IDX_SAAS_DISTRIBUTOR_ACCOUNT.getType().equals(value.getType())
                    || IndexTypeEnum.IDX_STATICS_MARKET_DATA.getType().equals(value.getType())
            ) {
                initSaasData(paasFormDataEsInitDTO);
                LOG.info(value.getIndex() + value.getType() + "===========成功");
            } else if ("404".equals(value.getType())) {
                LOG.info(value.getIndex() + value.getType() + "===========跳过");
            } else if (Objects.equals(ElasticConstant.SUB_FORM_TYPE, value.getType())) {
                if (paasFormDataEsInitDTO.isInclude()) {
                    initSubData(paasFormDataEsInitDTO);
                }
            } else {
                // 同步产品时加上条件，不然查不到父产品
                if(Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(),paasFormDataEsInitDTO.getBusinessType()) || Objects.equals(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(),paasFormDataEsInitDTO.getBusinessType())){
                    paasFormDataEsInitDTO.setFromInit(1);
                }
                init(paasFormDataEsInitDTO);
                LOG.info(value.getIndex() + value.getType() + "===========成功");
            }
        } catch (Exception e) {
            LOG.error("跳过异常=====" + value.getIndex() + "=============" + value.getType(), e);
        }
    }

    @Override
    public PaasFormDataEsInitVO initHighMapping(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        try {
            IndexTypeEnum indexTypeEnum = EsHelper.getIndexTypeEnum(paasFormDataEsMappingDTO);
            Integer textMax = EsAliasEnum.TEXT.getMax();
            if (Objects.equals(1, paasFormDataEsMappingDTO.getSpecial())) {
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CUSTOMER_SPECIAL;
                textMax = EsAliasEnum.TEXT.getSeparateIndexMax();
            }
            String indexName  = indexTypeEnum.getRealName();
            String type = indexTypeEnum.getType();
            JSONObject rootSetting = (JSONObject) JSONObject.parse(EsMappingConstant.ELASTIC_SETTINGS_ROOT);
            //----------------------上面是创建index  ，下面是mapping

            JSONObject mappingJson = (JSONObject) JSONObject.parse(EsMappingConstant.ELASTIC_MAPPING_ROOT);
            JSONObject properties = mappingJson.getJSONObject("properties");
            //TODO 梳理完后再提交
            mappingJson.put("dynamic","strict");
            //外层
            JSONObject outJsonObject = new JSONObject();
            //公有部分
            JSONObject newJsonObject = new JSONObject();

            for (int i = 1; i <= textMax; i++) {
                newJsonObject.put("data.text_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
            }
            for (int i = 1; i <= EsAliasEnum.NUM.getMax(); i++) {
                newJsonObject.put("data.num_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
            }
            for (int i = 1; i <= EsAliasEnum.LONG.getMax(); i++) {
                newJsonObject.put("data.long_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            }
            for (int i = 1; i <= EsAliasEnum.DATE.getMax(); i++) {
                newJsonObject.put("data.date_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            }
            for (int i = 1; i <= EsAliasEnum.GEO.getMax(); i++) {
                newJsonObject.put("data.geo_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LOCATION));
            }
            for (int i = 1; i <= EsAliasEnum.ADDRESS.getMax(); i++) {
                newJsonObject.put("data.address_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LOCATION));
            }
            for (int i = 1; i <= EsAliasEnum.FILE.getMax(); i++) {
                newJsonObject.put("data.file_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_NOT_ANALYZED));
            }
            //数组类型 内部定义为
            for (int i = 1; i <= EsAliasEnum.ARRAY.getMax(); i++) {
                newJsonObject.put("data.array_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            }
            //TODO 电话的需要预留
            JSONObject phoneInJsonObject = new JSONObject();
            for (int i = 1; i <= EsAliasEnum.PHONE_TEXT.getMax(); i++) {
                phoneInJsonObject.put("text_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
            }
            for (int i = 1; i <= EsAliasEnum.PHONE_NUM.getMax(); i++) {
                phoneInJsonObject.put("num_" + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
            }
            JSONObject phoneJsonObject = new JSONObject();
            phoneJsonObject.put("properties", phoneInJsonObject);

            //addTime
            outJsonObject.put("addTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            //lastConnectTime
            outJsonObject.put("updateTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            //lastConnectTime
            outJsonObject.put("serialNo", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
            outJsonObject.put("id", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("attr", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
            outJsonObject.put("creatorId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            //以上952
            outJsonObject.put("dataId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("corpid", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            outJsonObject.put("formId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("appId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("menuId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("departmentId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("flowStatus", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("del", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("ownerId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            //仅存储
            outJsonObject.put("esId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_NOT_ANALYZED));
            //TODO  data 平级字段的预留
            for (int i = 1; i <= SysAliasEnum.sysText.getMax(); i++) {
                newJsonObject.put(SysAliasEnum.sysText.getEsAlias() + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            }
            for (int i = 1; i <= SysAliasEnum.sysNum.getMax(); i++) {
                newJsonObject.put(SysAliasEnum.sysNum.getEsAlias() + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
            }
            for (int i = 1; i <= SysAliasEnum.sysLong.getMax(); i++) {
                newJsonObject.put(SysAliasEnum.sysLong.getEsAlias() + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            }
            for (int i = 1; i <= SysAliasEnum.sysDate.getMax(); i++) {
                newJsonObject.put(SysAliasEnum.sysDate.getEsAlias() + i, (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            }
            outJsonObject.putAll(newJsonObject);
            JSONObject json = new JSONObject();
            json.put(type, mappingJson);
            String relations;
            String teamRelate = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" + "[\"" + ElasticConstant.TEAM_TYPE+ "\"]}}";
            String subRelate = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" + "[\"" + ElasticConstant.SUB_FORM_TYPE+ "\"]}}";
            String teamAndSubRelate = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" + "[\"" +  ElasticConstant.TEAM_TYPE+ "\", \""
                    + ElasticConstant.SUB_FORM_TYPE+ "\"]}}";
            String noSubRelate = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":[]}}";
            switch (indexTypeEnum){
                case IDX_FORM_DATA:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_REIMBURSEMENT_FORM:
                case IDX_SAAS_EXPENSE:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_SAAS_CUSTOMER:
                case IDX_SAAS_CUSTOMER_SPECIAL:
                    if(Objects.equals(ProBaseConfig.getProjectName(), ProVersionEnum.PRD.getAlias()) && !Objects.equals(1, paasFormDataEsMappingDTO.getSpecial())){
                        rootSetting.getJSONObject("index").put("number_of_shards","20");
                    }
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    //客户电话的特殊处理
                    outJsonObject.put("data.subForm_1", phoneJsonObject);
                    break;
                case IDX_SAAS_CONTRACT:
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" +
                            "[\"" +  ElasticConstant.TEAM_TYPE+ "\", \""
                            +IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType()  + "\", \""
                            +IndexTypeEnum.IDX_SAAS_CONTRACT_PERFORMANCE.getType() + "\", \""
                            +ElasticConstant.SUB_FORM_TYPE + "\"]}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(relations));
                    break;
                case IDX_SAAS_QUOTATION:
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_OUTSTOCK:
                case IDX_SAAS_CONTRACT_OUTSTOCK:
                case IDX_SAAS_RETURNED_PURCHASE_OUTSTOCK:
                case IDX_SAAS_OTHER_OUTSTOCK:
                case IDX_SAAS_PRODUCTION_MATERIEL_OUTSTOCK:
                case IDX_SAAS_WORK_ORDER_OUTSTOCK:
                    //联系电话
                    outJsonObject.put("data.subForm_3", phoneJsonObject);
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_CONTACT:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    //联系人电话的特殊处理
                    outJsonObject.put("data.subForm_1", phoneJsonObject);
                    break;
                case IDX_SAAS_INVOICE:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    // 发票信息和寄送信息做成单独子表单
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" +
                            "[\"" + IndexTypeEnum.IDX_SAAS_INVOICE_EXPRESS.getType() + "\", \""
                            + ElasticConstant.SUB_FORM_TYPE + "\"]}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(relations));
                    break;
                case IDX_SAAS_PURCHASE_INVOICE:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    // 发票信息和寄送信息做成单独子表单
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" +
                            "[\"" + IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS.getType() + "\", \""
                            + ElasticConstant.SUB_FORM_TYPE + "\"]}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(relations));
                    break;
                case IDX_SAAS_INSTOCK:
                case IDX_SAAS_PURCHASE_INSTOCK:
                case IDX_SAAS_REFUND_INSTOCK:
                case IDX_SAAS_OTHER_INSTOCK:
                case IDX_SAAS_PRODUCTION_INSTOCK:
                case IDX_SAAS_RETURNED_MATERIEL_INSTOCK:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_ASSEMBLE:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_PAYMENT:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_PAYMENT_SHEET:
                case IDX_SAAS_PAYPLAN_SHEET:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(FieldTypeEnum.SHEET_ALONE.getAlias(), JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put(FieldTypeEnum.SHEET_UUID.getAlias(), JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_PRODUCTION_ORDER:
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_PAY_PLAN:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_COMMUNICATE_PLAN:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_OPPORTUNITY:
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_BOM:
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_CREDIT_LIMIT:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_SAAS_CREDIT_FIXED_LIMIT:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_CREDIT_TEMPORARY_LIMIT:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_CREDIT_CARD_BILL:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_SAAS_CUSTOMER_COMMUNICATE:
                    if(Objects.equals(ProBaseConfig.getProjectName(), ProVersionEnum.PRD.getAlias())){
                        rootSetting.getJSONObject("index").put("number_of_shards","20");
                    }
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    outJsonObject.put("logType", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    break;
                case IDX_SAAS_SUPPLIER_COMMUNICATE:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    outJsonObject.put("logType", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    break;
                case IDX_SAAS_WORK_REPORT:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    // 今日计划
                    JSONObject thisPlanInObj = new JSONObject();
                    thisPlanInObj.put("text_1", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    // 状态: 0 / 1
                    thisPlanInObj.put("text_2", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    thisPlanInObj.put("num_1", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    JSONObject thisPlanObj = new JSONObject();
                    thisPlanObj.put("properties", thisPlanInObj);
                    outJsonObject.put("data.subForm_1", thisPlanObj);
                    // 明日计划
                    JSONObject nextPlanInObj = new JSONObject();
                    nextPlanInObj.put("text_1", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    thisPlanInObj.put("text_2", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    nextPlanInObj.put("num_1", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    JSONObject nextPlanObj = new JSONObject();
                    nextPlanObj.put("properties", nextPlanInObj);
                    outJsonObject.put("data.subForm_2", nextPlanObj);
                    break;
                case IDX_SAAS_PURCHASE:
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_RETURNED_PURCHASE:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_SUPPLIER_CONTACT:
                    outJsonObject.put("data.subForm_1", phoneJsonObject);
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_SUPPLIER:
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    outJsonObject.put("data.subForm_1", phoneJsonObject);
                    break;
                case IDX_SAAS_PRODUCT:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" +
                            "[\"" +  ElasticConstant.TEAM_TYPE+ "\", \""
                            +IndexTypeEnum.IDX_SAAS_PRODUCT_WAREHOUSE.getType()  + "\", \""
                            +IndexTypeEnum.IDX_SAAS_PRODUCT_STOCK_INFO.getType()+ "\", \""
                            +ElasticConstant.SUB_FORM_TYPE + "\"]}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(relations));
                    break;
                case IDX_SAAS_INVENTORY:
                case IDX_SAAS_TRANSFER:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_WAREHOUSE:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_REFUND:
//                    outJsonObject.put("coUserId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_WORK_ORDER:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put("outstockId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("allOutbound", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("status", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("nowStageId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("expectedTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("actualTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("startTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("endTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("closeTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("templateId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("type", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));

                    //联系电话的特殊处理
                    outJsonObject.put("data.subForm_1", phoneJsonObject);
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" +
                            "[\"" +  ElasticConstant.TEAM_TYPE+ "\", \""
                            +IndexTypeEnum.IDX_SAAS_WORK_ORDER_CC.getType()+ "\", \""
                            +ElasticConstant.SUB_FORM_TYPE + "\"]}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(relations));
                    break;
                case IDX_SAAS_MARKETING_ACTIVITY_MANAGEMENT:
                    outJsonObject.put("startTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("endTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_SAAS_PROMOTION_ACTIVITY_MANAGEMENT:
                    outJsonObject.put("startTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("endTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_SAAS_ORISTOCK:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_SAAS_MARKET_ACTIVITY:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_CLUE:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    //电话的特殊处理
                    outJsonObject.put("data.subForm_1", phoneJsonObject);
                    break;
                case IDX_SAAS_CUSTOMER_STATEMENT:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_SAAS_STATEMENT:
                    JSONObject checkDate = new JSONObject();
                    checkDate.put("startTime",JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    checkDate.put("endTime",JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    JSONObject date = new JSONObject();
                    date.put("properties", checkDate);
                    outJsonObject.put("data.subForm_1", date);
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" +
                            "[\"" +IndexTypeEnum.IDX_SAAS_CUSTOMER_STATEMENT_SNAPSHOT.getType() + "\"]}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(relations));
                    break;
                case IDX_SAAS_DISTRIBUTOR_ACCOUNT:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_ONLINE_PAYMENT_FLOW:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_SAAS_OTHER_INCOME:
                case IDX_SAAS_OTHER_EXPENSE:
                case IDX_SAAS_FUND_TRANSFER:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(subRelate));
                    break;
                case IDX_SAAS_COST_ADJUST:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(subRelate));
                    break;
                case IDX_WORK_ORDER_V2:
                    //联系电话的特殊处理
                    outJsonObject.put("data.subForm_1", phoneJsonObject);
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" +
                            "[\"" +  ElasticConstant.TEAM_TYPE+ "\", \""
                            +IndexTypeEnum.IDX_WORK_ORDER_V2_PRODUCT.getType()  + "\", \""
                            +ElasticConstant.SUB_FORM_TYPE + "\"]}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(relations));
                    break;
                case IDX_RECEIPT_ORDER:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":" +
                            "[\"" +  ElasticConstant.TEAM_TYPE+ "\", \""
                            +IndexTypeEnum.IDX_RECEIPT_ORDER_PRODUCT.getType()  + "\", \""
                            +ElasticConstant.SUB_FORM_TYPE + "\"]}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(relations));
                    break;
                case IDX_SERVICE_PROJECT:
                case IDX_SLA_LOG_DATA:
                    outJsonObject.put("serialNo", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                case IDX_SAAS_COMPETITOR:
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(teamAndSubRelate));
                    break;
                default:
                    break;
            }
            properties.putAll(outJsonObject);
            JSONObject rootJson = new JSONObject();
            rootJson.put("mappings", mappingJson);
            rootJson.put("settings", rootSetting);
            LOG.info("indexName==================="+indexName);
            LOG.info("settingAndMapping============="+JSON.toJSONString(rootJson, SerializerFeature.DisableCircularReferenceDetect));
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            request.source(rootJson);
            CreateIndexResponse createIndexResponse = xbbElasticsearchRestTemplate.getRestHighLevelClient(indexName).indices().create(request, RequestOptions.DEFAULT);
            boolean acknowledged = createIndexResponse.isAcknowledged();
            if(acknowledged !=true){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            LOG.warn("=============建立es索引成功=============");
        } catch (Exception e) {
            LOG.error("mapping创建失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return paasFormDataEsInitVO;
    }


    @Override
    public PaasFormDataEsInitVO initHighMappingTest(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        try {
            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_STATICS_MARKET_DATA;
            String indexName  = indexTypeEnum.getRealName();
            String type = indexTypeEnum.getType();
            JSONObject rootSetting = (JSONObject) JSONObject.parse(EsMappingConstant.ELASTIC_SETTINGS_ROOT);
            //----------------------上面是创建index  ，下面是mapping
            String noSubRelate = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":[]}}";
            JSONObject mappingJson = (JSONObject) JSONObject.parse(EsMappingConstant.ELASTIC_MAPPING_ROOT);
            JSONObject properties = mappingJson.getJSONObject("properties");
            mappingJson.put("dynamic","strict");
            //外层
            JSONObject outJsonObject = new JSONObject();
            outJsonObject.put("dataId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("corpid", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            outJsonObject.put("marketId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("marketType", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            outJsonObject.put("marketName", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            outJsonObject.put("marketEndTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            outJsonObject.put("actualCost", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
            outJsonObject.put("clueId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("clueStatus", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            outJsonObject.put("clueStage", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            outJsonObject.put("clueAddTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            outJsonObject.put("customerId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("saleOpportunityId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("saleMoney", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
            outJsonObject.put("saleStage", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            outJsonObject.put("contractId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("contractMoney", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
            outJsonObject.put("addTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            outJsonObject.put("updateTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            outJsonObject.put("del", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
            //仅存储
            outJsonObject.put("esId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_NOT_ANALYZED));
            JSONObject json = new JSONObject();
            json.put(type, mappingJson);
            properties.putAll(outJsonObject);
            JSONObject rootJson = new JSONObject();
            rootJson.put("mappings", mappingJson);
            rootJson.put("settings", rootSetting);
            LOG.info("settingAndMapping============="+JSON.toJSONString(rootJson, SerializerFeature.DisableCircularReferenceDetect));
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            request.source(rootJson);
            CreateIndexResponse createIndexResponse = xbbElasticsearchRestTemplate.getRestHighLevelClient(indexName).indices().create(request, RequestOptions.DEFAULT);
            boolean acknowledged = createIndexResponse.isAcknowledged();
            if(acknowledged !=true){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            LOG.warn("=============建立es索引成功=============");
        } catch (Exception e) {
            LOG.error("mapping创建失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return paasFormDataEsInitVO;
    }

    @Override
    public BaseVO deleteMapping(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) throws XbbException {
        List<Integer> businessTypeList = paasFormDataEsMappingDTO.getBusinessTypeList();
        for (IndexTypeEnum indexTypeEnum : IndexTypeEnum.getAllEnum()) {
            if (businessTypeList.contains(indexTypeEnum.getCode())) {
                String esIndex = indexTypeEnum.getRealName();
                //删除索引
                try {
                    xbbElasticsearchRestTemplate.deleteIndex(esIndex);
                    LOG.error("删除索引===============================================" + indexTypeEnum.getCode());
                } catch (XbbException e) {
                    LOG.error(SystemErrorCodeEnum.API_ERROR_100001.getMsg(), e);
                }
            }
        }
        LOG.error("delete mapping===============================================over");
        return new BaseVO();
    }

    @Override
    public PaasFormDataEsInitVO initMappingAll(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        Set<String> indexTypeEnumSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (IndexTypeEnum indexTypeEnum : IndexTypeEnum.getAllEnum()) {
            if(indexTypeEnumSet.contains(indexTypeEnum.getIndex())){
                //不处理，跳过
            }else {
                indexTypeEnumSet.add(indexTypeEnum.getIndex());
                String esIndex = indexTypeEnum.getRealName();
                //删除索引
                /*try {
                    xbbElasticsearchRestTemplate.deleteIndex(esIndex);
                } catch (XbbException e) {
                    LOG.error(SystemErrorCodeEnum.API_ERROR_100001.getMsg(),e);
                }*/


                Integer index = indexTypeEnum.getCode();
                paasFormDataEsMappingDTO.setBusinessType(index);
                try {
                    boolean saasFlag = isSaasFlag(indexTypeEnum);
                    if(saasFlag){
                        initSaasMapping(paasFormDataEsMappingDTO);
                    }else {
                        initHighMapping(paasFormDataEsMappingDTO);
                    }
                } catch (XbbException e) {
                    LOG.error(SystemErrorCodeEnum.API_ERROR_100001.getMsg(),e);
                }
            }
        }
        return paasFormDataEsInitVO;
    }

    public boolean isSaasFlag(IndexTypeEnum indexTypeEnum) {
        return Objects.equals(indexTypeEnum.getCode(), IndexTypeEnum.IDX_PAY_BALANCE.getCode())
                || Objects.equals(indexTypeEnum.getCode(),IndexTypeEnum.IDX_PAYMENT_BALANCE.getCode())
                 || Objects.equals(indexTypeEnum.getCode(),IndexTypeEnum.IDX_CALL_CENTER_CALL_LOG.getCode())
                    || Objects.equals(indexTypeEnum.getCode(), IndexTypeEnum.IDX_FUND_ACCOUNT_FLOW.getCode())
                        || Objects.equals(indexTypeEnum.getCode(), IndexTypeEnum.IDX_STATICS_MARKET_DATA.getCode());
    }

    @Override
    public PaasFormDataEsInitVO initSaasMapping(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        HttpEntity httpEntity = null;
        try {
            IndexTypeEnum indexTypeEnum = EsHelper.getIndexTypeEnum(paasFormDataEsMappingDTO);
            String indexName =  indexTypeEnum.getRealName();
            JSONObject mappingJson = (JSONObject) JSONObject.parse(EsMappingConstant.ELASTIC_MAPPING_ROOT);
            JSONObject properties = mappingJson.getJSONObject("properties");
            //外层
            JSONObject outJsonObject = new JSONObject();
            outJsonObject.put("id", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            outJsonObject.put("corpid", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
            outJsonObject.put("addTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            outJsonObject.put("updateTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
            outJsonObject.put("del", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
            String noSubRelate = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType()+ "\":[]}}";
            String relations;
            switch (indexTypeEnum) {
                case IDX_CALL_CENTER_CALL_LOG:
                    outJsonObject.put("userId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put("refId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("refType", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("refName", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("moduleType", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("callTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("duration", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("ringTime", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("agentPhoneNum", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put("anotherPhoneNum", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put("type", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("result", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("isSynced", JSONObject.parse(EsMappingConstant.MAPPING_FOR_BOOLEAN));
                    outJsonObject.put("code", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("note", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("callUuid", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("recordUrl", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("translatePlatform", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("recordContent", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("translateData", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("callId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("instanceId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("hangUp", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("answer", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("callProcess", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("userName", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("skillGroupIds", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("skillGroupNames", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("callSource", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_PAYMENT_BALANCE:
                    outJsonObject.put("appId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("menuId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("formId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("ownerId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("departmentId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("creatorId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("customerId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("advancePaymentBalance", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
                    //处理父子关系层
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType() + "\":\"" + ElasticConstant.TEAM_TYPE + "\"}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(relations));
                    break;
                case IDX_PAY_BALANCE:
                    outJsonObject.put("appId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("menuId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("formId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("ownerId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("departmentId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("creatorId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("supplierId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("supplierName", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("advancePayBalance", JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
                    //处理父子关系层
                    relations = "{\"type\":\"join\",\"relations\":{\"" + indexTypeEnum.getType() + "\":\"" + ElasticConstant.TEAM_TYPE + "\"}}";
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, (JSONObject) JSONObject.parse(relations));
                    break;
                case IDX_FUND_ACCOUNT_FLOW:
                    outJsonObject.put("creatorId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("type", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("sheetId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("accountId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("sheetTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("sheetAmount", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_STATICS_MARKET_DATA:
                    outJsonObject.put("dataId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("marketId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("marketType", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("marketName", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("marketEndTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("actualCost", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
                    outJsonObject.put("clueId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("clueStatus", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("clueStage", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("clueAddTime", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DATE_SECOND));
                    outJsonObject.put("customerId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("saleOpportunityId", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("saleMoney", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_DOUBLE));
                    outJsonObject.put("saleStage", (JSONObject) JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    //仅存储
                    outJsonObject.put("esId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_NOT_ANALYZED));
                    break;
                case IDX_SAAS_KNOWLEDGE_DATA:
                    outJsonObject.put("appendix", JSONObject.parse(EsMappingConstant.MAPPING_FOR_NOT_ANALYZED));
                    outJsonObject.put("catalogueId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("knowledgeBaseId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("title", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("expandConsult", JSONObject.parse(EsMappingConstant.KNOWLEDGE_MAPPING_FOR_TEXT));
                    outJsonObject.put("keywords", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("label", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("content", JSONObject.parse(EsMappingConstant.KNOWLEDGE_MAPPING_FOR_TEXT));
                    outJsonObject.put("status", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("dataId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("usageCount", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("creatorId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("updateId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                    break;
                case IDX_CONTRACT_COMPARE:
                    outJsonObject.put("compareContractFile", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put("compareContractName", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put("compareDataId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("compareStatus", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("creatorId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("formType", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put("resultUrl", JSONObject.parse(EsMappingConstant.MAPPING_FOR_TEXT));
                    outJsonObject.put("standardContractFile", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put("standardContractName", JSONObject.parse(EsMappingConstant.MAPPING_FOR_STRING_SORT));
                    outJsonObject.put("standardDataId", JSONObject.parse(EsMappingConstant.MAPPING_FOR_LONG));
                    outJsonObject.put(ElasticConstant.MY_JOIN_FIELD, JSONObject.parse(noSubRelate));
                default:
                    break;
            }
            properties.putAll(outJsonObject);
            JSONObject rootJson = new JSONObject();
            rootJson.put("mappings", mappingJson);
            JSONObject rootSetting = (JSONObject) JSONObject.parse(EsMappingConstant.ELASTIC_SETTINGS_ROOT);
            rootJson.put("settings", rootSetting);
            LOG.info("indexName=====================" + indexName);
            LOG.info("settingAndMapping============="+JSON.toJSONString(rootJson, SerializerFeature.DisableCircularReferenceDetect));
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            request.source(rootJson);
            CreateIndexResponse createIndexResponse = xbbElasticsearchRestTemplate.getRestHighLevelClient(indexName).indices().create(request, RequestOptions.DEFAULT);
            boolean acknowledged = createIndexResponse.isAcknowledged();
            if(acknowledged !=true){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
        } catch (Exception e) {
            LOG.error("mapping创建失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }finally {
            if (Objects.nonNull(httpEntity)) {
                try {
                    ((NStringEntity) httpEntity).close();
                }catch (Exception e) {
                    LOG.error("mapping创建失败", e);
                }
            }
        }
        return paasFormDataEsInitVO;
    }

    @Override
    public PaasFormDataEsInitVO initSaasData(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        long timeStart = DateTimeUtil.getInt();
        try {
            LOG.info("paasFormDataEsInitDTO:=========" + paasFormDataEsInitDTO.getBusinessType()+"====="+ paasFormDataEsInitDTO.getSaasMark() +"======"+ paasFormDataEsInitDTO.toString());
            PaasFormDataEsMappingDTO paasFormDataEsMappingDTO = new PaasFormDataEsMappingDTO();
            Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
            if(byCorpid != null && Objects.equals(0,byCorpid)){
                paasFormDataEsInitDTO.setCorpid(null);
            }
            BeanUtil.copyProperties(paasFormDataEsInitDTO, paasFormDataEsMappingDTO);
             if (paasFormDataEsMappingDTO.getSaasMark().equals(SaasMarkEnum.PAAS.getCode())) {
                return paasFormDataEsInitVO;
            }
            Integer pageSize = paasFormDataEsInitDTO.getPageSize();
            if (pageSize == null) {
                paasFormDataEsInitDTO.setPageSize(SizeConstant.PAGE_SIZE);
            }
            IndexTypeEnum indexTypeEnum = EsHelper.getIndexTypeEnum(paasFormDataEsMappingDTO);
            if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_FORM_DATA_TEAM)) {
                //现在paas业务也有团队需求
                indexTypeEnum.setPaasTeamIndexTypeEnum(indexTypeEnum, SaasMarkEnum.PAAS.getCode());
            }
            Integer businessType = paasFormDataEsMappingDTO.getBusinessType();
            if (businessType == null || businessType.equals(0)) {
                LOG.error("businessType为空");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            JSONObject mapping  = getMappingMap(indexTypeEnum);
            Set<String> outKeySet = mapping.keySet();
            Set<String> dataKeySet = null;
            if(mapping.getJSONObject("data")!=null && !mapping.getJSONObject("data").isEmpty()){
                dataKeySet = mapping.getJSONObject("data").getJSONObject("properties").keySet();
            }
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            if (Objects.equals(businessType, IndexTypeEnum.IDX_STATICS_MARKET_DATA.getCode())) {
                xbbRefTypeEnum = XbbRefTypeEnum.MARKET_ACTIVITY_STATIC;
            }
            String value = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ELASTICSEARCH_INDEX.getAlias(), CompanyConfigEnum.ELASTICSEARCH_INDEX.getAlias(), "0", "0", RedisTimeConstant.TEN_MINUTES);
            Set<String> corpidSet = new HashSet<>();
            if (StringUtil.isNotEmpty(value)) {
                corpidSet = new HashSet<>(JSON.parseArray(value, String.class));
            }

            Map<String, Object> params = BeanUtil.convertBean2Map(paasFormDataEsInitDTO, true);

            params.put("orderByStr", "id");
            boolean flag = true;
            while (flag) {
                List list = null;
                list = teamHelp.getList(xbbRefTypeEnum, params, list);
                if (list == null || list.isEmpty()) {
                    flag = false;
                } else {
                    //大于上次最大的id
                    teamHelp.setIdGte(xbbRefTypeEnum, params, list);
                    LOG.info("businessType:" + xbbRefTypeEnum.getCode() + " max id :" + params.get("idGte"));
                    List<InsertDTO> insertList = new ArrayList<>();
                    boolean needTransf = false;
                    List<PaasFormDataEntity> paasFormDataEntityList =null;
                    switch (xbbRefTypeEnum){
                        case MARKET_ACTIVITY_STATIC:
                        case CALL_CENTER_CALL_LOG:
                        case PREPAYMENT_BALANCE:
                        case PREPAY_BALANCE:
                        case FUND_ACCOUNT_FLOW:
                            for (Object object : list) {
                                InsertDTO insertDTO = new InsertDTO();
                                insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
                                //
                                teamHelp.setInsertDTO(xbbRefTypeEnum, object, insertDTO);
                                insertDTO.setIndexTypeEnum(indexTypeEnum);
                                excludeKey(outKeySet, dataKeySet, insertDTO);
                                insertList.add(insertDTO);
                            }
                            break;
                        case CONTRACT_PERFORMANCE:
                            needTransf = true;
                            paasFormDataEntityList = transferSubFormHelper.transferContractPerformanceToFormDataList(list);
                            break;
                        case PRODUCT_WAREHOUSE:
                            needTransf = true;
                            paasFormDataEntityList = transferSubFormHelper.transferProductWarehouseToFormDataList(list);
                            break;
                        case PRODUCT_STOCK_INFO:
                            needTransf = true;
                            paasFormDataEntityList = transferSubFormHelper.transferProductStockToFormDataList(list);
                            break;
                        case CONTRACT_PRODUCT:
                            needTransf = true;
                            paasFormDataEntityList = transferSubFormHelper.transferContractProductToFormDataList(list);
                            break;
                        case PRODUCT_TEAM:
                            needTransf = true;
                            paasFormDataEntityList = transferSubFormHelper.transferUserAndDepTeamToFormDataList(indexTypeEnum, list);
                            break;
                        case DISTRIBUTOR_ACCOUNT:
                            needTransf = true;
                            paasFormDataEntityList = transferSubFormHelper.transferDistributorAccountToFormDataList(list);
                            break;
                        case COMPETITOR_TEAM:
                            needTransf = true;
                            paasFormDataEntityList = transferSubFormHelper.transferUserAndDepTeamToFormDataList(indexTypeEnum, list);
                            break;
                        default:
                            //团队相关的放到default里处理
                            needTransf = true;
                            try {
                                paasFormDataEntityList = transferSubFormHelper.transferUserTeamToFormDataList(indexTypeEnum, list);
                            } catch (Exception e) {
                                LOG.error("========"+indexTypeEnum,e);
                            }
                            break;
                    }
                    if(needTransf){
                        if(CollectionsUtil.isNotEmpty(paasFormDataEntityList)){
                            if (corpidSet.contains(paasFormDataEntityList.get(0).getCorpid()) && Objects.equals(XbbRefTypeEnum.CUSTOMER_TEAM.getCode(), businessType)) {
                                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CUSTOMER_TEAM_SPECIAL;
                            }
                            for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntityList) {
                                InsertDTO insertDTO = new InsertDTO();
                                insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
                                //
                                insertDTO.setIndexTypeEnum(indexTypeEnum);
                                insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, indexTypeEnum);
                                excludeKey(outKeySet, dataKeySet, insertDTO);
                                insertList.add(insertDTO);
                            }
                        }
                    }
                    if(paasFormDataEsInitDTO.isAsync()){
                        paasEsModel.insertBatchAsync(insertList,WriteRequest.RefreshPolicy.NONE,false);
                    }else {
                        paasEsModel.insertBatch(insertList,WriteRequest.RefreshPolicy.NONE,false);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("初始化失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        LOG.info("-----------time end:" + (DateTimeUtil.getInt() - timeStart));
        LOG.error("初始化成功" + paasFormDataEsInitDTO.getBusinessType());
        return paasFormDataEsInitVO;
    }



    @Override
    public PaasFormDataEsInitVO deleteAllData(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws XbbException {
        PaasFormDataEsInitVO dataInitVO = new PaasFormDataEsInitVO();
        try {
            for (IndexTypeEnum indexTypeEnum : IndexTypeEnum.getAllEnum()) {
                try {
                    deleteByQueryCorpid(indexTypeEnum,paasFormDataEsInitDTO.getCorpid());
                } catch (Exception e) {
                    LOG.error("删除失败的索引================"+indexTypeEnum,e);
                    //TODO 已存在则跳过
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            throw  new XbbException(BiErrorCodeEnum.API_ERROR_241011);
        }
        return dataInitVO;
    }

    @Override
    public PaasFormDataEsInitVO initByCorpidListAndBusinessTypeList(PaasFormDataEsInitByCorpidListAndBusinessTypeListDTO paasFormDataEsInitByCorpidListAndBusinessTypeListDTO) {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        List<String> corpidList= paasFormDataEsInitByCorpidListAndBusinessTypeListDTO.getCorpidList();

        List<Integer> businessTypeList = paasFormDataEsInitByCorpidListAndBusinessTypeListDTO.getBusinessTypeList();
        List<IndexTypeEnum> indexTypeEnumList = new ArrayList<>();
        businessTypeList.forEach(businessType-> indexTypeEnumList.add(IndexTypeEnum.getByCode(businessType)));
        if (businessTypeList.contains(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            indexTypeEnumList.add(IndexTypeEnum.IDX_SAAS_CUSTOMER_SPECIAL);
        }
        if (businessTypeList.contains(XbbRefTypeEnum.CUSTOMER_TEAM.getCode())) {
            indexTypeEnumList.add(IndexTypeEnum.IDX_SAAS_CUSTOMER_TEAM_SPECIAL);
        }
        if (businessTypeList.contains(XbbRefTypeEnum.CUSTOMER_SUBFORM.getCode())) {
            indexTypeEnumList.add(IndexTypeEnum.IDX_SAAS_CUSTOMER_SUB_SPECIAL);
        }
        if (CollectionUtils.isNotEmpty(corpidList)) {
            for (String corpid : corpidList) {
                for (IndexTypeEnum value : indexTypeEnumList) {
                    PaasFormDataEsInitDTO paasFormDataEsInitDTO = new PaasFormDataEsInitDTO();
                    paasFormDataEsInitDTO.setByCorpid(1);
                    paasFormDataEsInitDTO.setCorpid(corpid);
                    paasFormDataEsInitDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    paasFormDataEsInitDTO.setBusinessType(value.getCode());
                    paasFormDataEsInitDTO.setUserId(paasFormDataEsInitByCorpidListAndBusinessTypeListDTO.getUserId());
                    paasFormDataEsInitDTO.setXbbCode(paasFormDataEsInitByCorpidListAndBusinessTypeListDTO.getXbbCode());
                    paasFormDataEsInitDTO.setFromInit(1);
                    try {
                        if ("my_team".equals(value.getType()) || "product_warehouse".equals(value.getType()) || "product_stock_info".equals(value.getType())
                                || "call_center_call_log".equals(value.getType()) || "contract_performance".equals(value.getType()) || "my_cc".equals(value.getType())
                                || "my_evaluation".equals(value.getType()) || "my_product".equals(value.getType())
                                || IndexTypeEnum.IDX_PAYMENT_BALANCE.getType().equals(value.getType()) || IndexTypeEnum.IDX_PAYMENT_BALANCE_TEAM.getType().equals(value.getType())
                                || IndexTypeEnum.IDX_PAY_BALANCE.getType().equals(value.getType()) || IndexTypeEnum.IDX_PAY_BALANCE_TEAM.getType().equals(value.getType())
                        ) {
                            initSaasData(paasFormDataEsInitDTO);
                            LOG.info(value.getIndex() + value.getType() + "===========成功");
                        } else if ("404".equals(value.getType())) {
                            LOG.info(value.getIndex() + value.getType() + "===========跳过");
                        } else {
                            init(paasFormDataEsInitDTO);
                            LOG.info(value.getIndex() + value.getType() + "===========成功");
                        }
                    } catch (Exception e) {
                        LOG.error("跳过异常=====", e);
                    }
                }
            }
        } else {
            for (IndexTypeEnum value : indexTypeEnumList) {
                PaasFormDataEsInitDTO paasFormDataEsInitDTO = new PaasFormDataEsInitDTO();
                paasFormDataEsInitDTO.setByCorpid(0);
                paasFormDataEsInitDTO.setCorpid(paasFormDataEsInitByCorpidListAndBusinessTypeListDTO.getCorpid());
                paasFormDataEsInitDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                paasFormDataEsInitDTO.setBusinessType(value.getCode());
                paasFormDataEsInitDTO.setUserId(paasFormDataEsInitByCorpidListAndBusinessTypeListDTO.getUserId());
                paasFormDataEsInitDTO.setXbbCode(paasFormDataEsInitByCorpidListAndBusinessTypeListDTO.getXbbCode());
                paasFormDataEsInitDTO.setFromInit(1);
                try {
                    if ("my_team".equals(value.getType()) || "product_warehouse".equals(value.getType()) || "product_stock_info".equals(value.getType())
                            || "call_center_call_log".equals(value.getType()) || "contract_performance".equals(value.getType()) || "my_cc".equals(value.getType())
                            || "my_evaluation".equals(value.getType()) || "my_product".equals(value.getType())
                            || IndexTypeEnum.IDX_PAYMENT_BALANCE.getType().equals(value.getType()) || IndexTypeEnum.IDX_PAYMENT_BALANCE_TEAM.getType().equals(value.getType())
                            || IndexTypeEnum.IDX_PAY_BALANCE.getType().equals(value.getType()) || IndexTypeEnum.IDX_PAY_BALANCE_TEAM.getType().equals(value.getType())
                    ) {
                        initSaasData(paasFormDataEsInitDTO);
                        LOG.info(value.getIndex() + value.getType() + "===========成功");
                    } else if ("404".equals(value.getType())) {
                        LOG.info(value.getIndex() + value.getType() + "===========跳过");
                    } else {
                        init(paasFormDataEsInitDTO);
                        LOG.info(value.getIndex() + value.getType() + "===========成功");
                    }
                } catch (Exception e) {
                    LOG.error("跳过异常=====", e);
                }
            }
        }

        LOG.info("初始化结束success=====");
        return paasFormDataEsInitVO;
    }

    @Deprecated
    private void deleteByQueryCorpid(IndexTypeEnum indexTypeEnum,String corpid)   {
        //TODO  2019年7月1日17:34:57    是否要做scrooll
        HttpEntity httpEntity = null;
        try {
            httpEntity = new NStringEntity("{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"corpid.keyword\":\"" +
                    corpid +
                    "\"}}]}}}", ContentType.APPLICATION_JSON);
            String index = indexTypeEnum.getIndex();
            //TODO
//             xbbElasticsearchRestTemplate.getRestClient(index).performRequest("POST", index + "/" + indexTypeEnum.getType() + "/_delete_by_query", Collections.emptyMap(), httpEntity);
        } catch (Exception e) {
            LOG.error("",e);
        } finally {
            if (Objects.nonNull(httpEntity)) {
                try {
                    ((NStringEntity) httpEntity).close();
                } catch (Exception e) {
                    LOG.error("dataWarehouse.deleteByQuery",e);
                }
            }
        }
    }

    @Override
    public PaasFormDataEsInitVO addAlias(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) throws XbbException {
        PaasFormDataEsInitVO dataInitVO = new PaasFormDataEsInitVO();
        HttpEntity httpEntity = null;
        try {
            IndexTypeEnum indexTypeEnum = EsHelper.getIndexTypeEnum(paasFormDataEsMappingDTO);
            if (Objects.equals(1, paasFormDataEsMappingDTO.getSpecial())) {
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CUSTOMER_SPECIAL;
            }
            String alias = indexTypeEnum.getIndex();
            String index = indexTypeEnum.getRealName();
            Request request = new Request("GET","/" + index + "/_alias/");
            Response response = xbbElasticsearchRestTemplate.getRestClient(index).performRequest(request);
            JSONObject entityJson = (JSONObject) JSONObject.parse(EntityUtils.toString(response.getEntity()));
            JSONObject result = entityJson.getJSONObject(index).getJSONObject("aliases");
            String msg = "";
            if(result!=null && !result.isEmpty()){
                Set<String> key = result.keySet();
                msg = key.toString();

            }
            Request addRequest = new Request("POST","/_aliases");
            httpEntity = new NStringEntity("{\"actions\":[{\"add\":{\"index\":\"" + index +
                    "\",\"alias\":\"" + alias +
                    "\"}}]}", ContentType.APPLICATION_JSON);
            addRequest.setEntity(httpEntity);
            xbbElasticsearchRestTemplate.getRestClient(index).performRequest(addRequest);
            dataInitVO.setMsg(msg + alias);
        } catch (Exception e) {
            LOG.error("",e);
            throw  new XbbException(BiErrorCodeEnum.API_ERROR_241011);
        } finally {
            if (Objects.nonNull(httpEntity)) {
                try {
                    ((NStringEntity) httpEntity).close();
                } catch (Exception e) {
                    LOG.error("",e);
                }
            }
        }
        return dataInitVO;
    }
    @Override
    public PaasFormDataEsInitVO addAllAlias(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) throws XbbException {
        PaasFormDataEsInitVO dataInitVO = new PaasFormDataEsInitVO();
        HttpEntity httpEntity = null;
        try {
            JSONArray jsonArray = new JSONArray();
            for (IndexTypeEnum indexTypeEnum : IndexTypeEnum.getAllEnum()) {
                JSONObject addJson = JSONObject.parseObject("{\"add\":{\"index\":\"" + indexTypeEnum.getRealName() + "\",\"alias\":\"" + indexTypeEnum.getIndex() + "\"}}");
                jsonArray.add(addJson);
            }

            Request addRequest = new Request("POST","/_aliases");
            httpEntity = new NStringEntity("{\"actions\":" + jsonArray.toJSONString()+
                    "}", ContentType.APPLICATION_JSON);
            addRequest.setEntity(httpEntity);
            //使用客户的索引获取client
//            xbbElasticsearchRestTemplate.getRestClient(IndexTypeEnum.IDX_SAAS_CUSTOMER.getIndex()).performRequest(addRequest);
        }  catch (Exception e) {
            LOG.error("",e);
            throw  new XbbException(BiErrorCodeEnum.API_ERROR_241011);
        } finally {
            if (Objects.nonNull(httpEntity)) {
                try {
                    ((NStringEntity) httpEntity).close();
                } catch (Exception e) {
                    LOG.error("",e);
                }
            }
        }
        return dataInitVO;
    }


    @Override
    public PaasFormDataEsInitVO initOriginData(PaasFormOriginalDataInitDTO paasFormOriginalDataInitDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        try {
            Integer businessType = paasFormOriginalDataInitDTO.getBusinessType();
            //用作增量处理
            Long updateTimeGte = paasFormOriginalDataInitDTO.getUpdateTimeGte();
            String oneCorpid = paasFormOriginalDataInitDTO.getOneCorpid();
            Integer byCorpid = paasFormOriginalDataInitDTO.getByCorpid();
            List<String> exceptCorpids = paasFormOriginalDataInitDTO.getExceptCorpids();
            Integer onlyPaas = paasFormOriginalDataInitDTO.getOnlyPaas();
            String startCorpid = paasFormOriginalDataInitDTO.getStartCorpid();
            if (Objects.isNull(businessType)) {
                // 如果没传businessType就进行所有业务的处理
                List<IndexTypeEnum> subIndexType = Arrays.asList(
                        IndexTypeEnum.IDX_SUB_FORM_DATA,
                        IndexTypeEnum.IDX_SAAS_CUSTOMER_SUB,
                        IndexTypeEnum.IDX_SAAS_CUSTOMER_SUB_SPECIAL,
                        IndexTypeEnum.IDX_SAAS_CONTRACT_SUB,
                        IndexTypeEnum.IDX_SAAS_QUOTATION_SUB,
                        IndexTypeEnum.IDX_SAAS_OUTSTOCK_SUB,
                        IndexTypeEnum.IDX_SAAS_CONTACT_SUB,
                        IndexTypeEnum.IDX_SAAS_INVOICE_SUB,
                        IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB,
                        IndexTypeEnum.IDX_SAAS_INSTOCK_SUB,
                        IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB,
                        IndexTypeEnum.IDX_SAAS_PAYMENT_SUB,
                        IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_SUB,
                        IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB,
                        IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB,
                        IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB,
                        IndexTypeEnum.IDX_SAAS_OTHER_INCOME_SUB,
                        IndexTypeEnum.IDX_SAAS_OTHER_EXPENSE_SUB,
                        IndexTypeEnum.IDX_SAAS_FUND_TRANSFER_SUB,
                        IndexTypeEnum.IDX_SAAS_COMMUNICATE_PLAN_SUB,
                        IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB,
                        IndexTypeEnum.IDX_SAAS_BOM_SUB,
                        IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB,
                        IndexTypeEnum.IDX_SAAS_SUPPLIER_COMMUNICATE_SUB,
                        IndexTypeEnum.IDX_SAAS_WORK_REPORT_SUB,
                        IndexTypeEnum.IDX_SAAS_PURCHASE_SUB,
                        IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB,
                        IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB,
                        IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB,
                        IndexTypeEnum.IDX_SAAS_PRODUCT_SUB,
                        IndexTypeEnum.IDX_SAAS_INVENTORY_SUB,
                        IndexTypeEnum.IDX_SAAS_TRANSFER_SUB,
                        IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB,
                        IndexTypeEnum.IDX_SAAS_REFUND_SUB,
                        IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB,
                        IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB,
                        IndexTypeEnum.IDX_RECEIPT_ORDER_SUB,
                        IndexTypeEnum.IDX_WORK_ORDER_V2_SUB,
                        IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_SUB);

                if (Objects.equals(byCorpid, 1)) {
                    if (Objects.nonNull(oneCorpid)) {
                        for (IndexTypeEnum indexTypeEnum : subIndexType) {
                            if (Objects.equals(onlyPaas, 1)) {
                                if (!indexTypeEnum.equals(IndexTypeEnum.IDX_SUB_FORM_DATA)) {
                                    continue;
                                }
                            }
                            LOG.info("init original data start, now index is:" + indexTypeEnum + " , corpid=" + oneCorpid);
                            transferOriginData(updateTimeGte, indexTypeEnum, oneCorpid);
                            LOG.info("init original data end, now index is:" + indexTypeEnum + " , corpid=" + oneCorpid);
                        }
                    } else {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "oneCorpid不可为null");
                    }
                } else {
                    String corpidGte = "0";
                    Map<String, Object> param = new HashMap<>();
                    param.put("del", 0);
                    param.put("start", 0);
                    param.put("pageNum", 1000);
                    param.put("columns", "corpid");
                    param.put("orderByStr", "corpid");
                    if (Objects.nonNull(startCorpid)) {
                        param.put("corpidGte", startCorpid);
                    }
                    while (true) {
                        List<CompanyEntity> companyEntities = companyModel.findEntitys(param);
                        if (Objects.isNull(companyEntities) || companyEntities.size() == 0) {
                            break;
                        }
                        corpidGte = companyEntities.get(companyEntities.size() - 1).getCorpid();
                        param.put("corpidGte", corpidGte);
                        for (CompanyEntity companyEntity : companyEntities) {
                            if (Objects.nonNull(exceptCorpids)) {
                                if (exceptCorpids.contains(companyEntity.getCorpid())) {
                                    continue;
                                }
                            }
                            for (IndexTypeEnum indexTypeEnum : subIndexType) {
                                if (Objects.equals(onlyPaas, 1)) {
                                    if (!indexTypeEnum.equals(IndexTypeEnum.IDX_SUB_FORM_DATA)) {
                                        continue;
                                    }
                                }
                                LOG.info("init original data start, now index is:" + indexTypeEnum + " , corpid=" + companyEntity.getCorpid());
                                transferOriginData(updateTimeGte, indexTypeEnum, companyEntity.getCorpid());
                                LOG.info("init original data end, now index is:" + indexTypeEnum + " , corpid=" + companyEntity.getCorpid());
                            }
                        }
                    }
                }


            } else {
                if (Objects.equals(byCorpid, 1)) {
                    if (Objects.nonNull(oneCorpid)) {
                        IndexTypeEnum indexTypeEnum = indexTypeModel.getByCode(oneCorpid, businessType);
                        if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SUB_FORM_DATA)) {
                            indexTypeEnum.setPaasTeamIndexTypeEnum(indexTypeEnum, SaasMarkEnum.PAAS.getCode());
                        }
                        LOG.info("init original data start, now index is:" + indexTypeEnum + " , corpid=" + oneCorpid);
                        if (Objects.equals(onlyPaas, 1)) {
                            if (indexTypeEnum.equals(IndexTypeEnum.IDX_SUB_FORM_DATA)) {
                                transferOriginData(updateTimeGte, indexTypeEnum, oneCorpid);
                            }
                        } else {
                            transferOriginData(updateTimeGte, indexTypeEnum, oneCorpid);
                        }
                        LOG.info("init original data end, now index is:" + indexTypeEnum + " , corpid=" + oneCorpid);
                    } else {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "oneCorpid不可为null");
                    }
                } else {
                    // 处理指定的业务
                    String corpidGte = "0";
                    Map<String, Object> param = new HashMap<>();
                    param.put("del", 0);
                    param.put("start", 0);
                    param.put("pageNum", 1000);
                    param.put("columns", "corpid");
                    param.put("orderByStr", "corpid");
                    if (Objects.nonNull(startCorpid)) {
                        param.put("corpidGte", startCorpid);
                    }
                    while (true) {
                        List<CompanyEntity> companyEntities = companyModel.findEntitys(param);
                        if (Objects.isNull(companyEntities) || companyEntities.size() == 0) {
                            break;
                        }
                        corpidGte = companyEntities.get(companyEntities.size() - 1).getCorpid();
                        param.put("corpidGte", corpidGte);
                        for (CompanyEntity companyEntity : companyEntities) {
                            if (Objects.nonNull(exceptCorpids)) {
                                if (exceptCorpids.contains(companyEntity.getCorpid())) {
                                    continue;
                                }
                            }
                            IndexTypeEnum indexTypeEnum = indexTypeModel.getByCode(companyEntity.getCorpid(), businessType);
                            if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SUB_FORM_DATA)) {
                                indexTypeEnum.setPaasTeamIndexTypeEnum(indexTypeEnum, SaasMarkEnum.PAAS.getCode());
                            }
                            LOG.info("init original data start, now index is:" + indexTypeEnum + " , corpid=" + companyEntity.getCorpid());
                            if (Objects.equals(onlyPaas, 1)) {
                                if (indexTypeEnum.equals(IndexTypeEnum.IDX_SUB_FORM_DATA)) {
                                    transferOriginData(updateTimeGte, indexTypeEnum, companyEntity.getCorpid());
                                }
                            } else {
                                transferOriginData(updateTimeGte, indexTypeEnum, companyEntity.getCorpid());
                            }
                            LOG.info("init original data end, now index is:" + indexTypeEnum + " , corpid=" + companyEntity.getCorpid());
                        }
                    }
                }
            }
            LOG.info("init original data success");
        } catch (Exception e) {
            LOG.error("init original data fail", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return paasFormDataEsInitVO;
    }



    /**
     * paas团队成员数据同步
     *
     * @param paasFormDataEsInitDTO
     * @return
     */
    @Override
    public PaasFormDataEsInitVO paasTeamDataInit(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        try {
            LOG.info("paasFormDataEsInitDTO:=========" + paasFormDataEsInitDTO.getBusinessType()+"====="+ paasFormDataEsInitDTO.getSaasMark() +"======"+ paasFormDataEsInitDTO.toString());
            PaasFormDataEsMappingDTO paasFormDataEsMappingDTO = new PaasFormDataEsMappingDTO();
            Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
            if(byCorpid != null && Objects.equals(0,byCorpid)){
                paasFormDataEsInitDTO.setCorpid(null);
            }
            BeanUtil.copyProperties(paasFormDataEsInitDTO, paasFormDataEsMappingDTO);
            Integer pageSize = paasFormDataEsInitDTO.getPageSize();
            if (pageSize == null) {
                paasFormDataEsInitDTO.setPageSize(SizeConstant.PAGE_SIZE);
            }
            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_FORM_DATA_TEAM;
            indexTypeEnum.setPaasTeamIndexTypeEnum(indexTypeEnum, SaasMarkEnum.PAAS.getCode());
            JSONObject mapping  = getMappingMap(indexTypeEnum);
            Set<String> outKeySet = mapping.keySet();
            Set<String> dataKeySet = null;
            if(mapping.getJSONObject("data")!=null && !mapping.getJSONObject("data").isEmpty()){
                dataKeySet = mapping.getJSONObject("data").getJSONObject("properties").keySet();
            }
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(paasFormDataEsInitDTO.getBusinessType());
            Map<String, Object> params = BeanUtil.convertBean2Map(paasFormDataEsInitDTO, true);
            params.put("orderByStr", "id");
            boolean flag = true;
            while (flag) {
                List list = null;
                list = teamHelp.getList(xbbRefTypeEnum, params, list);
                if (list == null || list.isEmpty()) {
                    flag = false;
                } else {
                    //大于上次最大的id
                    teamHelp.setIdGte(xbbRefTypeEnum, params, list);
                    LOG.info("businessType:" + xbbRefTypeEnum.getCode() + " max id :" + params.get("idGte"));
                    List<InsertDTO> insertList = new ArrayList<>();
                    boolean needTransf = false;
                    List<PaasFormDataEntity> paasFormDataEntityList =null;
                    switch (xbbRefTypeEnum){
                        case PAAS_TEAM:
                            needTransf = true;
                            paasFormDataEntityList = transferSubFormHelper.transferUserTeamToFormDataList(indexTypeEnum, list);
                            break;
                        default:
                            break;
                    }
                    if(needTransf){
                        if(CollectionsUtil.isNotEmpty(paasFormDataEntityList)){
                            for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntityList) {
                                InsertDTO insertDTO = new InsertDTO();
                                insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
                                //
                                insertDTO.setIndexTypeEnum(indexTypeEnum);
                                insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, indexTypeEnum);
                                excludeKey(outKeySet, dataKeySet, insertDTO);
                                insertList.add(insertDTO);
                            }
                        }
                    }
                    if(paasFormDataEsInitDTO.isAsync()){
                        paasEsModel.insertBatchAsync(insertList,WriteRequest.RefreshPolicy.NONE,false);
                    }else {
                        paasEsModel.insertBatch(insertList,WriteRequest.RefreshPolicy.NONE,false);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("初始化失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        LOG.error("初始化成功" + paasFormDataEsInitDTO.getBusinessType());
        return paasFormDataEsInitVO;
    }

    /**
     *  团队成员需求用于paas表单提前刷数据
     *
     * @param paasFormDataEsInitDTO
     * @return
     */
    @Override
    public PaasFormDataEsInitVO teamMembersPaasFormDataInit(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws XbbException {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        long start = DateTimeUtil.getInt();
        try {
            Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
            if(byCorpid != null && Objects.equals(0,byCorpid)){
                paasFormDataEsInitDTO.setCorpid(null);
            }
            Integer pageSize = paasFormDataEsInitDTO.getPageSize();
            if (pageSize == null) {
                paasFormDataEsInitDTO.setPageSize(SizeConstant.PAGE_SIZE);
            }
            PaasFormDataEsMappingDTO paasFormDataEsMappingDTO = new PaasFormDataEsMappingDTO();
            BeanUtil.copyProperties(paasFormDataEsInitDTO, paasFormDataEsMappingDTO);
            String indexVersion = paasFormDataEsInitDTO.getIndexVersion();
            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_FORM_DATA;
            indexTypeEnum.setPaasTeamIndexTypeEnum(indexTypeEnum, SaasMarkEnum.PAAS.getCode());
            JSONObject mapping = getMappingMap(indexTypeEnum);
            Set<String> outKeySet = mapping.keySet();
            Set<String> dataKeySet = mapping.getJSONObject("data").getJSONObject("properties").keySet();
            JSONObject subForm = mapping.getJSONObject("data").getJSONObject("properties").getJSONObject("subForm_1");
            JSONObject subFormSec = mapping.getJSONObject("data").getJSONObject("properties").getJSONObject("subForm_2");
            Set<String> subFormKeySet = null;
            Set<String> subFormKeySecSet = null;
            if(subForm != null && !subForm.isEmpty()){
                subFormKeySet = subForm.getJSONObject("properties").keySet();
            }
            if(subFormSec != null && !subFormSec.isEmpty()){
                subFormKeySecSet = subFormSec.getJSONObject("properties").keySet();
            }
            if(Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(),paasFormDataEsInitDTO.getBusinessType()) || Objects.equals(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(),paasFormDataEsInitDTO.getBusinessType())){
                paasFormDataEsInitDTO.setFromInit(1);
            }
            Map<String, Object> params = BeanUtil.convertBean2Map(paasFormDataEsInitDTO, true,true);
            //计算出最大maxId
            Long maxId = paasFormDataModel.getMaxId(params);
            params.put("orderByStr", "id");
            boolean flag = true;
            int num = 0;
            while (flag) {
                if (num > 0 && (num % 100 == 0)) {
                    Thread.sleep(paasFormDataEsInitDTO.getSleepTime()*1000L);
                }
                List list = initDataHelp.getList(paasFormDataEsMappingDTO.getBusinessType(),paasFormDataEsMappingDTO.getSaasMark() ,params,paasFormDataEsInitDTO.getFromInit(), null);
                if (list == null || list.isEmpty()) {
                    flag = false;
                } else {
                    //大于上次最大的id
                    Object o = list.get(list.size() - 1);
                    PaasFormDataEntity paasFormDataEntity = (PaasFormDataEntity) o;

                    LOG.info("总进度已处理=====id:{} / maxId:{}" , paasFormDataEntity.getId(), maxId);
                    params.put("idGte", paasFormDataEntity.getId());
                    List<InsertDTO> insertList = new ArrayList<>();
                    for (Object object : list) {
                        try {
                            PaasFormDataEntity entity = (PaasFormDataEntity) object;
                            InsertDTO insertDTO = new InsertDTO();
                            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
                            insertDTO.setEsId(entity.getCorpid() + "_" + entity.getId());
                            entity.setDataId(entity.getId());
                            Map<String, Object> source = BeanUtil.convertBean2Map(entity, false, true);
                            JSONObject data = (JSONObject) source.get("data");
                            if(Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(),paasFormDataEsInitDTO.getBusinessType())){
                                data.put(ProductEnum.INSTRUCTION.getAttr(),"");
                            }
                            //特殊子表单内数据的清理
                            JSONArray subFormDataArray = data.getJSONArray("subForm_1");
                            if(subFormDataArray != null && !subFormDataArray.isEmpty()){
                                if(CollectionsUtil.isNotEmpty(subFormKeySet)){
                                    for (int i = 0; i < subFormDataArray.size(); i++) {
                                        JSONObject subFormData = subFormDataArray.getJSONObject(i);
                                        subFormData.keySet().retainAll(subFormKeySet);
                                    }
                                }
                            }
                            //工作报告可能有第二个子表单
                            JSONArray subFormDataSecArray = data.getJSONArray("subForm_2");
                            if(subFormDataSecArray != null && !subFormDataSecArray.isEmpty()){
                                if(CollectionsUtil.isNotEmpty(subFormKeySecSet)){
                                    for (int i = 0; i < subFormDataSecArray.size(); i++) {
                                        JSONObject subFormDataSec = subFormDataSecArray.getJSONObject(i);
                                        subFormDataSec.keySet().retainAll(subFormKeySecSet);
                                    }
                                }
                            }
                            data.keySet().retainAll(dataKeySet);
                            source.keySet().retainAll(outKeySet);
                            source.put(ElasticConstant.MY_JOIN_FIELD,indexTypeEnum.getType());
                            insertDTO.setSource(source);
                            insertDTO.setIndexTypeEnum(indexTypeEnum, indexVersion);
                            insertList.add(insertDTO);
                        } catch (Exception e) {
                            LOG.error("==="+JSONObject.toJSONString(object),e);
                        }
                    }
                    if(paasFormDataEsInitDTO.isAsync()){
                        paasEsModel.insertBatchAsync(insertList,WriteRequest.RefreshPolicy.NONE,false);
                    }else{
                        paasEsModel.insertBatch(insertList,WriteRequest.RefreshPolicy.NONE,false);
                    }
                }
                num ++;
            }
        } catch (Exception e) {
            LOG.error("初始化失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.error("初始化成功" + paasFormDataEsInitDTO.getBusinessType());
        return paasFormDataEsInitVO;
    }

    /**
     * 删除paas的es索引，只用于团队成员需求，后续此脚本不能再使用
     *
     * @param paasFormDataEsMappingDTO
     * @return
     */
    @Override
    public BaseVO deletePaasMapping(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) {
       String indexName = ProBaseConfig.getEsName() + "idx_form_data";
       //删除索引
        try {
            xbbElasticsearchRestTemplate.deleteIndex(indexName);
            LOG.error("删除索引===============================================" + indexName);
        } catch (XbbException e) {
            LOG.error(SystemErrorCodeEnum.API_ERROR_100001.getMsg(), e);
        }
        return new BaseVO();
    }

    /**
     * 获取paas表单数据，用于团队功能进行比较数据
     *
     * @param paasFormDataEsMappingDTO
     * @return
     */
    @Override
    public String checkEsDataNum(PaasFormDataEsMappingDTO paasFormDataEsMappingDTO) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        IndexTypeEnum indexTypeEnum = EsHelper.getIndexTypeEnum(paasFormDataEsMappingDTO);
        long count = paasEsModel.count(boolQueryBuilder , indexTypeEnum);
        return String.valueOf(count);
    }

        private void transferOriginData(Long updateTimeGte, IndexTypeEnum indexTypeEnum, String corpid) throws XbbException {
        List<Integer> businessTypes = new ArrayList<>();
        IModel iModel = null;
        boolean isPaas = false;
        switch (indexTypeEnum) {
            case IDX_SUB_FORM_DATA:
                iModel = paasFormDataModel;
                isPaas = true;
//                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PAAS.getCode());
                break;
            case IDX_SAAS_CUSTOMER_SUB:
            case IDX_SAAS_CUSTOMER_SUB_SPECIAL:
                iModel = customerModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.CUSTOMER.getCode());
                break;
            case IDX_SAAS_CONTRACT_SUB:
                iModel = contractModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.CONTRACT.getCode());
                break;
            case IDX_SAAS_QUOTATION_SUB:
                iModel = quotationModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.QUOTATION.getCode());
                break;
            case IDX_SAAS_OUTSTOCK_SUB:
                iModel = outstockModel;
                businessTypes = Arrays.asList(RedundantTemplateTypeEnum.OUTSTOCK.getCode(),
                        RedundantTemplateTypeEnum.CONTRACT_OUTSTOCK.getCode(),
                        RedundantTemplateTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode(),
                        RedundantTemplateTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode(),
                        RedundantTemplateTypeEnum.OTHER_OUTSTOCK.getCode(),
                        RedundantTemplateTypeEnum.WORK_ORDER_OUTSTOCK.getCode());
                break;
            case IDX_SAAS_CONTACT_SUB:
                iModel = contactModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.CONTACT.getCode());
                break;
            case IDX_SAAS_INVOICE_SUB:
                iModel = invoiceModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.INVOICE.getCode());
                break;
            case IDX_SAAS_PURCHASE_INVOICE_SUB:
                iModel = purchaseInvoiceModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PURCHASE_INVOICE.getCode());
                break;
            case IDX_SAAS_INSTOCK_SUB:
                iModel = instockModel;
                businessTypes = Arrays.asList(RedundantTemplateTypeEnum.INSTOCK.getCode(),
                        RedundantTemplateTypeEnum.PURCHASE_INSTOCK.getCode(),
                        RedundantTemplateTypeEnum.REFUND_INSTOCK.getCode(),
                        RedundantTemplateTypeEnum.OTHER_INSTOCK.getCode(),
                        RedundantTemplateTypeEnum.PRODUCTION_INSTOCK.getCode(),
                        RedundantTemplateTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode());
                break;
            case IDX_SAAS_ASSEMBLE_SUB:
                iModel = assembleModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.ASSEMBLE.getCode());
                break;
            case IDX_SAAS_PAYMENT_SUB:
                iModel = paymentModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PAYMENT.getCode());
                break;
            case IDX_SAAS_PAYMENT_SHEET_SUB:
                iModel = paymentSheetModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PAYMENT_SHEET.getCode());
                break;
            case IDX_SAAS_PAYPLAN_SHEET_SUB:
                iModel = payPlanSheetModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PAY_SHEET.getCode());
                break;
            case IDX_SAAS_PRODUCTION_ORDER_SUB:
                iModel = productionOrderModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PRODUCTIONORDER.getCode());
                break;
            case IDX_SAAS_PAY_PLAN_SUB:
                iModel = payPlanModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PAY_PLAN.getCode());
                break;
            case IDX_SAAS_COMMUNICATE_PLAN_SUB:
                iModel = communicatePlanModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.COMMUNICATE_PLAN.getCode());
                break;
            case IDX_SAAS_OPPORTUNITY_SUB:
                iModel = opportunityModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.SALES_OPPORTUNITY.getCode());
                break;
            case IDX_SAAS_BOM_SUB:
                iModel = bomBillModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.BOMBILL.getCode());
                break;
            case IDX_SAAS_CUSTOMER_COMMUNICATE_SUB:
                iModel = customerCommunicateModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.COMMUNICATE.getCode());
                break;
            case IDX_SAAS_SUPPLIER_COMMUNICATE_SUB:
                iModel = supplierCommunicateModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.JXC_COMMUNICATE.getCode());
                break;
            case IDX_SAAS_WORK_REPORT_SUB:
                iModel = workReportModel;
                businessTypes = Arrays.asList(RedundantTemplateTypeEnum.WORKREPORT.getCode(),
                        RedundantTemplateTypeEnum.WORKREPORT_DAILY.getCode(),
                        RedundantTemplateTypeEnum.WORKREPORT_WEEKLY.getCode(),
                        RedundantTemplateTypeEnum.WORKREPORT_MONTHLY.getCode());
                break;
            case IDX_SAAS_PURCHASE_SUB:
                iModel = purchaseModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PURCHASE.getCode());
                break;
            case IDX_SAAS_RETURNED_PURCHASE_SUB:
                iModel = returnedPurchaseModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.RETURNED_PURCHASE.getCode());
                break;
            case IDX_SAAS_SUPPLIER_CONTACT_SUB:
                iModel = supplierContactModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.SUPPLIER_CONTACT.getCode());
                break;
            case IDX_SAAS_SUPPLIER_SUB:
                iModel = supplierModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.SUPPLIER.getCode());
                break;
            case IDX_SAAS_PRODUCT_SUB:
                iModel = productModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.PRODUCT.getCode());
                break;
            case IDX_SAAS_INVENTORY_SUB:
                iModel = inventoryModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.INVENTORY.getCode());
                break;
            case IDX_SAAS_TRANSFER_SUB:
                iModel = transferModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.TRANSFER.getCode());
                break;
            case IDX_SAAS_WAREHOUSE_SUB:
                iModel = warehouseModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.WAREHOUSE.getCode());
                break;
            case IDX_SAAS_REFUND_SUB:
                iModel = refundModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.REFUND.getCode());
                break;
            case IDX_SAAS_OTHER_INCOME_SUB:
                iModel = otherIncomeModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.OTHER_INCOME.getCode());
                break;
            case IDX_SAAS_OTHER_EXPENSE_SUB:
                iModel = otherExpenseModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.OTHER_EXPENSE.getCode());
                break;
            case IDX_SAAS_FUND_TRANSFER_SUB:
                iModel = fundTransferModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.FUND_TRANSFER.getCode());
                break;
            case IDX_SAAS_WORK_ORDER_SUB:
                iModel = workOrderModel;
                break;
            case IDX_SAAS_COST_ADJUST_SUB:
                iModel = costAdjustModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.COST_ADJUST.getCode());
                break;
            case IDX_RECEIPT_ORDER_SUB:
                iModel = costAdjustModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.RECEIPT_ORDER.getCode());
                break;
            case IDX_WORK_ORDER_V2_SUB:
                iModel = costAdjustModel;
                businessTypes = Collections.singletonList(RedundantTemplateTypeEnum.RECEIPT_ORDER.getCode());
                break;
            default:
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        List<Long> formIdIn = new ArrayList<>();

        Map<String, Object> param = new HashMap<>();
        param.put("del", 0);
        param.put("corpid", corpid);
        if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB)) {
            List<WorkOrderExplainEntity> workOrderExplainEntities = workOrderExplainModel.findEntitys(param);
            for (WorkOrderExplainEntity workOrderExplainEntity : workOrderExplainEntities) {
                List<FieldAttrEntity> fieldList = JSON.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
                for (FieldAttrEntity fieldAttrEntity : fieldList) {
                    String attr = fieldAttrEntity.getAttr();
                    if (attr.contains("subForm") && !Objects.equals(attr, WorkOrderEnum.CONTACT_INFORMATION.getAttr())) {
                        formIdIn.add(workOrderExplainEntity.getFormId());
                        break;
                    }
                }

            }

        } else {
            if (isPaas) {
                param.put("saasMark", SaasMarkEnum.PAAS.getCode());
            } else {
                param.put("saasMark", SaasMarkEnum.SAAS.getCode());
                param.put("businessTypeIn", businessTypes);
            }
            List<PaasFormExplainEntity> paasFormExplainEntities = paasFormExplainModel.findEntitys(param);
            for (PaasFormExplainEntity paasFormExplainEntity : paasFormExplainEntities) {
                List<FieldAttrEntity> fieldList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                for (FieldAttrEntity fieldAttrEntity : fieldList) {
                    String attr = fieldAttrEntity.getAttr();
                    if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_CUSTOMER_SUB) || Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_CUSTOMER_SUB_SPECIAL)) {
                        if (attr.contains("subForm") && !Objects.equals(attr, CustomerManagementEnum.CONTACT_PHONE.getAttr()) && !Objects.equals(attr, CustomerManagementEnum.PHONE.getAttr())) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_CONTACT_SUB)) {
                        if (attr.contains("subForm") && !Objects.equals(attr, ContactEnum.PHONE.getAttr())) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_INVOICE_SUB)) {
                        if (attr.contains("subForm")) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB)) {
                        if (attr.contains("subForm")) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_COMMUNICATE_PLAN_SUB)) {
                        if (attr.contains("subForm") && !Objects.equals(attr, CommunicatePlanEnum.CONTACT_WAY.getAttr())) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_WORK_REPORT_SUB)) {
                        if (attr.contains("subForm") && !Objects.equals(attr, WorkReportFieldEnum.THIS_PLAN.getAttr()) && !Objects.equals(attr, WorkReportFieldEnum.NEXT_PLAN.getAttr())) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB)) {
                        if (attr.contains("subForm") && !Objects.equals(SupplierContactEnum.PHONE.getAttr(), attr)) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB)) {
                        if (attr.contains("subForm") && !Objects.equals(attr, SupplierEnum.PHONE.getAttr())) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_PRODUCT_SUB)) {
                        if (attr.contains("subForm") && !Objects.equals(attr, ProductEnum.STOCK_NOTIFY.getAttr())) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    }else {
                        if (attr.contains("subForm")) {
                            formIdIn.add(paasFormExplainEntity.getFormId());
                            break;
                        }
                    }
                }

            }


        }
        if (!formIdIn.isEmpty()) {
            Integer start = 0;
            //每次查询100条
            Integer pageNum = 500;
            Long idGte = 0L;
            param.clear();
            param.put("del", 0);
            param.put("corpid", corpid);
            param.put("formIdIn", formIdIn);

            Integer entitysCount = iModel.getEntitysCount(param);

            param.put("start", start);
            param.put("pageNum", pageNum);
            param.put("orderByStr", "id");
            if (Objects.nonNull(updateTimeGte)) {
                param.put("updateTimeStart", updateTimeGte);
            }

            Long count = 0L;
            while (true) {
                param.put("idGte", idGte);
                List<PaasFormDataEntity> paasFormDataEntityExts = iModel.findEntitysWithoutSub(param);
                if (paasFormDataEntityExts == null || paasFormDataEntityExts.size() == 0) {
                    break;
                }
                idGte = paasFormDataEntityExts.get(paasFormDataEntityExts.size() - 1).getId();
                count = count + paasFormDataEntityExts.size();
                LOG.info("init Original data process: " + count + "/" + entitysCount + " , indextype=" + indexTypeEnum + " , corpid=" + corpid);
                if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_INVOICE_SUB)) {
                    List<Long> ids = new ArrayList<>();
                    for (PaasFormDataEntity paasFormDataEntityExt : paasFormDataEntityExts) {
                        paasFormSubDataModel.transferSingleSubForm(paasFormDataEntityExt, IndexTypeEnum.IDX_SAAS_INVOICE_EXPRESS);
                        paasFormSubDataModel.transferSubForm(paasFormDataEntityExt, indexTypeEnum);
                        ids.add(paasFormDataEntityExt.getId());
                    }
                    if (ids.size() > 0) {
                        paasFormSubDataModel.deleteBatchByDataId(ids, corpid, IndexTypeEnum.IDX_SAAS_INVOICE_SUB, DelEnum.DELETE);
                    }

                    filterSubId(paasFormDataEntityExts);

                    paasFormSubDataModel.insertBatchSingleSubFormData(paasFormDataEntityExts, IndexTypeEnum.IDX_SAAS_INVOICE_EXPRESS);
                    paasFormSubDataModel.insertBatchSubFormData(paasFormDataEntityExts, indexTypeEnum);


                } else if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB)) {
                    List<Long> ids = new ArrayList<>();
                    for (PaasFormDataEntity paasFormDataEntityExt : paasFormDataEntityExts) {
                        paasFormSubDataModel.transferSingleSubForm(paasFormDataEntityExt, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
                        paasFormSubDataModel.transferSubForm(paasFormDataEntityExt, indexTypeEnum);
                        ids.add(paasFormDataEntityExt.getId());
                    }
                    if (ids.size() > 0) {
                        paasFormSubDataModel.deleteBatchByDataId(ids, corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB, DelEnum.DELETE);
                    }
                    filterSubId(paasFormDataEntityExts);

                    paasFormSubDataModel.insertBatchSingleSubFormData(paasFormDataEntityExts, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
                    paasFormSubDataModel.insertBatchSubFormData(paasFormDataEntityExts, indexTypeEnum);
                } else {
                    List<Long> ids = new ArrayList<>();
                    for (PaasFormDataEntity paasFormDataEntityExt : paasFormDataEntityExts) {
                        paasFormSubDataModel.transferSubForm(paasFormDataEntityExt, indexTypeEnum);
                        if (Objects.nonNull(paasFormDataEntityExt.getSubFormData())) {
                            ids.add(paasFormDataEntityExt.getId());
                        }

                    }
                    if (ids.size() > 0) {
                        paasFormSubDataModel.deleteBatchByDataId(ids, corpid, indexTypeEnum, DelEnum.DELETE);
                    }

                    filterSubId(paasFormDataEntityExts);

                    paasFormSubDataModel.insertBatchSubFormData(paasFormDataEntityExts, indexTypeEnum);
                }
            }
        }
    }

    private void filterSubId(List<PaasFormDataEntity> paasFormDataEntityExts) {
        for (PaasFormDataEntity paasFormDataEntityExt : paasFormDataEntityExts) {
            JSONObject subFormData = paasFormDataEntityExt.getSubFormData();
            JSONObject singleSubFormData = paasFormDataEntityExt.getSingleSubFormData();
            if (Objects.nonNull(subFormData)) {
                subFormData.forEach((k, v) -> {
                    JSONArray jsonArray = (JSONArray) v;
                    Iterator<Object> iterator = jsonArray.iterator();
                    while (iterator.hasNext()) {
                        JSONObject jsonObject = (JSONObject) iterator.next();
                        jsonObject.remove("subId");
                        if (jsonObject.isEmpty()) {
                            iterator.remove();
                        }
                    }
                });
            }
            if (Objects.nonNull(singleSubFormData)) {
                singleSubFormData.forEach((k, v) -> {
                    JSONArray jsonArray = (JSONArray) v;
                    Iterator<Object> iterator = jsonArray.iterator();
                    while (iterator.hasNext()) {
                        JSONObject jsonObject = (JSONObject) iterator.next();
                        jsonObject.remove("subId");
                        if (jsonObject.isEmpty()) {
                            iterator.remove();
                        }
                    }
                });
            }
        }
    }


    /**
     * 同步paas子表单，只适用于团队成员需求；其它有同步paas子表单的需求请用
     * curl  http://127.0.0.1:2019/pro/v1/esInit/initAllByBuss  -X POST -H 'Content-type: application/json' -d '{"userId":"1","corpid":"1","platform":"web","xbbCode":"123456","saasMark":1,"businessType":2,"byCorpid":0,"businessTypeList":[2], "include":true}'
     *
     * @param paasFormDataEsInitDTO
     * @return
     * @throws Exception
     */
    @Override
    public PaasFormDataEsInitVO initPaasSubData(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws Exception {
        PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
        PaasFormDataEsMappingDTO paasFormDataEsMappingDTO = new PaasFormDataEsMappingDTO();
        Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
        if(byCorpid != null && Objects.equals(0,byCorpid)){
            paasFormDataEsInitDTO.setCorpid(null);
        }
        BeanUtil.copyProperties(paasFormDataEsInitDTO, paasFormDataEsMappingDTO);
        Integer pageSize = paasFormDataEsInitDTO.getPageSize();
        if (pageSize == null) {
            paasFormDataEsInitDTO.setPageSize(SizeConstant.PAGE_SIZE);
        }
        IndexTypeEnum indexTypeEnum = EsHelper.getIndexTypeEnum(paasFormDataEsMappingDTO);
        //因为现在刷数据都是同步别名刷数据，所以这边需要做些特殊处理
        indexTypeEnum.setPaasTeamIndexTypeEnum(indexTypeEnum, SaasMarkEnum.PAAS.getCode());
        Integer businessType = paasFormDataEsMappingDTO.getBusinessType();
        if (businessType == null || businessType.equals(0)) {
            LOG.error("businessType为空");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        Map<String, Object> params = BeanUtil.convertBean2Map(paasFormDataEsInitDTO, true);
        Long maxId = paasFormSubDataModel.getMaxId(params);
        params.put("orderByStr", "id");
        boolean flag = true;
        long timeStart = DateTimeUtil.getInt();
        while (flag) {
            List<? extends PaasFormSubDataEntity> list = paasFormSubDataModel.getSubDataList(params, indexTypeEnum);
            if (list == null || list.isEmpty()) {
                flag = false;
            } else {
                LOG.info("总进度已处理=====id:{} / maxId:{}", list.get(list.size() - 1).getId(), maxId);
                params.put("idGte", list.get(list.size() - 1).getId());
                paasFormSubDataEsModel.insertBatch(list, indexTypeEnum);
            }

        }
        LOG.info("-----------time end:" + (DateTimeUtil.getInt() - timeStart));
        LOG.info("-----------/script/teamMembers/initPaasSubData over");
        return paasFormDataEsInitVO;
    }
}
